import api from '~/assets/js/common/api'
import cookieUtil from '~/assets/js/common/cookie'
export default function(context) {
  const { store, redirect, error, $axios, req } = context
  return $axios.post(api.user.info).then(({ data: { user } }) => {
    if (!user) {
      // 没有登录的话，从cookie中查看是否有cookie信息，再做一次登录
      let cookieStr = req.headers.cookie
      let pageCookie = cookieUtil.parseCookie(cookieStr)
      let param = ''
      if (pageCookie.uid) {
        return $axios
          .post(api.user.login, {
            isFreeLogin: true
          })
          .then(({ data: loginResult }) => {
            // 如果登录没成功，跳转到登录页面
            if (loginResult.state !== 0) {
              if (req.path.length > 1) {
                param = `?from=${encodeURIComponent(req.url)}`
              }
              redirect(`/login${param}`)
            } else {
              store.commit('user/SET_USER', loginResult.user)
            }
          })
      }
      if (req.path.length > 1) {
        param = `?from=${encodeURIComponent(req.url)}`
      }
      redirect(`/login${param}`)
    } else {
      // 放入登录用户信息
      store.commit('user/SET_USER', user)
    }
  })
}
